using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Xml.Linq;

namespace XmlDB
{
    public class XmlDB<T> where T:new()
    {

        private string _filePath = string.Empty;
        private XDocument _xmlDoc = null;
        public XmlDB(string filePath)
        {
            _filePath = filePath;
            _xmlDoc = new XDocument();
            _xmlDoc = XDocument.Load(filePath);
        }

        public List<T> GetAll()
        {
            int cont = 0;
            try
            {
                List<T> retval = new List<T>();
                foreach (XElement element in Utils.GetDataElements(_xmlDoc))
                {
                    retval.Add(Utils.Map<T>(element));
                    cont++;
                }
                return retval;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error parsing record number {0} in file '{1}'. {2}\r\n{3}", cont, _filePath, ex.Message, ex.StackTrace));
            }
            
        }

        public List<T> Get(Func<T, bool> filter)
        {
            int cont = 0;
            try
            {
                List<T> retval = new List<T>();
                T temp = default(T);
                foreach (XElement element in Utils.GetDataElements(_xmlDoc))
                {
                    temp = Utils.Map<T>(element);
                    if (filter(temp))
                        retval.Add(temp);
                    cont++;
                }
                return retval;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error filtering record number {0} in file '{1}'. {2}\r\n{3}",cont,_filePath,ex.Message,ex.StackTrace));
            }
        }

    }
}
